package org.elec.mac.gizwits;

import org.elec.mac.constants.Constants;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;

import lombok.extern.slf4j.Slf4j;

/**
 * Created by Bean on 2018/6/2.
 */
@Slf4j
@Component
public class GizWebSocketHeart {

    @Autowired
    private GizApi gizApi;

    @Value("${giz.login.header}")
    private String appId;

    @Value("${giz.login.username}")
    private String username;

    @Value("${giz.login.password}")
    private String password;

    @Scheduled(fixedRate = 60000)
    private void gizHeartTask() {
        if (Constants.webSocket != null) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("cmd", "ping");
            Constants.webSocket.send(jsonObject.toString());
            //log.info("ping");
        }
    }

    @Scheduled(fixedRate = 300000)
    private void gizLoginToken() throws IOException {
        if (Constants.gizToken.getExpire_at() > System.currentTimeMillis() / 1000 + 3600) {
            return;
        } else {
            Constants.gizToken = null;
            Constants.gizToken = gizApi.openApiLogin(appId, username, password);

            while(Constants.gizToken == null){
                log.error("登录失败，重试……");
                Constants.gizToken = gizApi.openApiLogin(appId, username, password);
            }
        }
    }
}
